/**
 * TranslateActions.java
 *
 * Copyright (C) 2009,  Tomislav Milkovic
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package extjsdyntran.servlets.actions;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import extjsdyntran.servlets.Constants;
import extjsdyntran.translation.ServiceTypes;
import extjsdyntran.translation.TranslationFactory;
import extjsdyntran.translation.ITranslationService;
import ws4is.engine.actions.AServletAction;
import ws4is.engine.enums.HTTPRequestType;
import ws4is.engine.utils.JsonUtil;

public final class TranslateActions extends AServletAction  {

	final static Logger logger = LoggerFactory.getLogger(TranslateActions.class);
	
	private String reload = null;
	private String language = null;
	private String translate = null;

	private final static String cmd = "cmd";
	private final static ArrayList<ServiceTypes> excludes = new ArrayList<ServiceTypes> ();
	
	{
		excludes.add(ServiceTypes.PROXY);
	}
	/******************************************
	 * 			POJO Methods     		      * 
	 ******************************************/	
	public void setReload(String reload) {
		this.reload = reload;
	}
	
	public void setLanguage(final String language){
		this.language = language;
	}
	
	public void setTranslate(final String translate){
		this.translate = translate;
	}		
		


	/******************************************
	 * 			overrides        		      * 
	 ******************************************/
	
	@Override
	public String preExecute(HTTPRequestType type, HttpServletRequest request) {
		return cmd;
	}
	
	@Override
	public void postExecute(HTTPRequestType type, String method, Exception e) {
		// TODO Auto-generated method stub
		
	}

	
	/******************************************
	 * 			HTTP-GET Methods		      * 
	 ******************************************/

	//test for remote service
	// TODO test specific service , if all services, return array of messages which service is working, if simple test just do all services	
	public void test(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
			setJsonResponseHeader(response);
			PrintWriter pw = getPrintWriter(response);
			Map<String,Boolean> result = TranslationFactory.test(); 
			String json = getJSONResponse(true, gson.toJson(result));
			pw.print(json);
			//pw.print(getJSONResponse(false, Constants.err4));
	}
	
	//get list of supported languages; reload translations if needed
	public void languages(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		setJsonResponseHeader(response); 
		PrintWriter pw = getPrintWriter(response);
		
		String editor=null;
		Cookie[] cookies = request.getCookies();
		if(cookies!=null)
			for (Cookie cookie : cookies){
				if("ext-tran-ed".equals(cookie.getName())){
					editor =  cookie.getValue();
					break;
				}
			} 
		
		//if not editor, exclude proxy services from list of supported languages
		Collection langs = null;
		if("true".equals(editor)){
			langs  = TranslationFactory.getLanguages(null);
		} else {
			langs =  TranslationFactory.getLanguages(excludes);
		}
		
		pw.print(gson.toJson(langs));		
		if (reload!=null) {
			TranslationFactory.reloadLanguages();
		}		
	}
	
	
	//client side before aplaying new translations asks for current service type;
	//if it is NORMAL service then do translation; this is support for Editor to not to start translation if proxy is selected 
	public void isNormalService(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
			setJsonResponseHeader(response);
			PrintWriter pw = getPrintWriter(response);

			if (language==null) {
				pw.print(getJSONResponse(false, Constants.err1));
				logger.warn(Constants.err5);
			}
				
			ITranslationService  transervice = TranslationFactory.getServiceByType(language, ServiceTypes.NORMAL);
			pw.print(getJSONResponse(transervice!=null, null));				

			return;						
	}
	
	//translate value to specified language	
	public void translate(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		setJsonResponseHeader(response);
		PrintWriter pw = getPrintWriter(response);

			if ((translate!=null)&&(language!=null)) {
				if(translate.length()==0) {
					pw.print("");
					return;
				}
				
				ITranslationService  transervice = TranslationFactory.getService(language);
								
				if(transervice==null) {
					logger.warn("Not a valid resource translation service for value {}",language);
					pw.print(getJSONResponse(false, Constants.err5));
					return;
				} 
				
				String resp = transervice.translate(translate,language);
				//not good as it will send unicode, not displayed well on page
				//pw.print(gson.toJson(resp));
				pw.print(JsonUtil.escape(resp));
				return;			
			} else{
				pw.print(getJSONResponse(false, Constants.err5));
				logger.warn(Constants.err5);
			}		
		
	}
	
	//request save translation cache to disk	
	public void save(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
			setJsonResponseHeader(response);
			PrintWriter pw = getPrintWriter(response);
			if (language == null) {
				pw.print(getJSONResponse(false, Constants.err1));
				return;
			};
			ITranslationService  transervice= TranslationFactory.getRealService(language);
			if (transervice.saveLanguages(language)) {
				pw.print(Constants.json_true);
			} else {
				pw.print(getJSONResponse(false, Constants.err6));
			}
	}
	
	//request load translation cache from disk
	public void load(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
			setJsonResponseHeader(response);				
			PrintWriter pw = getPrintWriter(response);
			if (language != null) {
				ITranslationService  transervice = TranslationFactory.getRealService(language);
				String s = transervice.getTranslationsToJson(language); 
				pw.print(s);
			}else {
				pw.print(getJSONResponse(false, Constants.err7));
			}	
	}



}
